/**
 * org.assess.oa.system.service.impl.TbDepartmentServiceImpl
 */
package org.assess.oa.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.assess.core.bean.node.TreeNode;
import org.assess.core.common.DateUtils;
import org.assess.core.service.BaseServiceImpl;
import org.assess.core.service.ServiceResult;
import org.assess.oa.system.bean.TbDepartment;
import org.assess.oa.system.dao.TbDepartmentDAO;
import org.assess.oa.system.service.TbDepartmentService;

import com.alibaba.fastjson.JSON;

/**
 * @description 部门管理的Service层实现类
 * @author XiaLongxiang
 * @createtime 2012-5-15 上午9:26:34
 */
public class TbDepartmentServiceImpl extends BaseServiceImpl implements TbDepartmentService {
    /** 日志对象 */
    private static Logger logger = Logger.getLogger(TbDepartmentServiceImpl.class);
    
    /** 操作部门表的DAO层对象 */
    private TbDepartmentDAO tbDepartmentDAO;
    
    public TbDepartment queryTbDepartmentByCode(TbDepartment department) {
        TbDepartment result = null;
        try {
            result = this.tbDepartmentDAO.queryTbDepartmentByCode(department.getDepartment_code(),
                    department.getValid_flag());
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String queryTbDepartmentAsList(TbDepartment department) {
        String result = "";
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            if (department != null) {
                parameters.put("parent_code", department.getParent_code());
                parameters.put("valid_flag", department.getValid_flag());
            }
            
            List<TbDepartment> records = this.tbDepartmentDAO.queryTbDepartmentAsList(parameters);
            result = super.toListPageString(1, 1, 1, "getDepartment_code", records);
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String queryTbDepartmentAsTreeStr(int depth, TbDepartment department) {
        String result = "";
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            if (department != null) {
                parameters.put("parent_code", department.getParent_code());
                parameters.put("valid_flag", department.getValid_flag());
            }
            List<TbDepartment> records = this.tbDepartmentDAO.queryTbDepartmentAsList(parameters);
            result = this.toTreePageString(depth, records);
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        
        return result;
    }
    
    public String listTbDepartmentAsScopeAll(String user_code) {
        String result = "";
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("valid_flag", "1");
            List<TbDepartment> all_records = this.tbDepartmentDAO.queryTbDepartmentAsList(parameters);
            List<TbDepartment> per_records = this.tbDepartmentDAO.queryTbDepartmentByUserCode(user_code);
            
            List<TreeNode> nodes = new ArrayList<TreeNode>();
            Map<String, TreeNode> map = new HashMap<String, TreeNode>();
            if (all_records != null && !all_records.isEmpty()) {
                List<TreeNode> _temps = new ArrayList<TreeNode>();
                for (TbDepartment dept : all_records) {
                    TreeNode node = new TreeNode();
                    node.setId(dept.getDepartment_code());
                    node.setName(dept.getDepartment_name());
                    node.setParent_id(dept.getParent_code());
                    node.setOpen(true);
                    _temps.add(node);
                    map.put(node.getId(), node);
                }
                
                for (TreeNode node : _temps) {
                    TreeNode pNode = map.get(node.getParent_id());
                    if (pNode != null) {
                        pNode.addNode(node);
                    }
                    else {
                        nodes.add(node);
                    }
                }
                
                if (per_records != null && !per_records.isEmpty()) {
                    for (TbDepartment dept : per_records) {
                        TreeNode node = map.get(dept.getDepartment_code());
                        if (node != null) {
                            node.setChecked(true);
                        }
                    }
                }
            }
            
            result = JSON.toJSONString(nodes);
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String queryTbDepartmentAsJsonArray(TbDepartment department) {
        String result = "";
        try {
            Map<String, Object> parameters = new HashMap<String, Object>();
            if (department != null) {
                parameters.put("parent_code", department.getParent_code());
                parameters.put("valid_flag", department.getValid_flag());
            }
            
            List<TbDepartment> records = this.tbDepartmentDAO.queryTbDepartmentAsList(parameters);
            result = JSON.toJSONString(records);
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    public String updateValid(TbDepartment department) throws Exception {
        String result = "";
        try {
            String[] department_codes = department.getDepartment_code().split(",");
            department.setModify_time(new Date());
            department.setModify_user(super.getLoginUserCode());
            for (String code : department_codes) {
                department.setDepartment_code(code);
                this.tbDepartmentDAO.updateTbDepartmentValid(department);
            }
            
            result = super.toResultString(true);
        }
        catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
        
        return result;
    }
    
    public ServiceResult saveTbDepartment(TbDepartment department, boolean edit) throws Exception {
        ServiceResult result = ServiceResult.error_unknown;
        try {
            if (edit) {
                department.setModify_time(new Date());
                department.setModify_user(super.getLoginUserCode());
                this.tbDepartmentDAO.update(department);
                result = ServiceResult.save_success;
            }
            else {
                TbDepartment record = this.tbDepartmentDAO.queryTbDepartmentByCode(department.getDepartment_code(), "");
                if (record == null) {
                    if (StringUtils.isBlank(department.getParent_code())) {
                        department.setParent_code("1");
                    }
                    department.setValid_flag("1");
                    department.setCreate_time(new Date());
                    department.setCreate_user(super.getLoginUserCode());
                    this.tbDepartmentDAO.insert(department);
                    result = ServiceResult.save_success;
                }
                else {
                    result = ServiceResult.save_error_code_duplicate;
                }
            }
        }
        catch (Exception ex) {
            result = ServiceResult.save_error_server;
            logger.error(ex);
            throw ex;
        }
        return result;
    }
    
    public String checkTbDepartment(TbDepartment department) {
        String result = "";
        try {
            TbDepartment record = this.tbDepartmentDAO.queryTbDepartmentByCode(department.getDepartment_code(), "");
            result = super.toCheckExistsString(record != null && StringUtils.isNotEmpty(record.getDepartment_code()));
        }
        catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }
    
    private String toTreePageString(int depth, List<TbDepartment> records) {
        int size = records != null ? records.size() : 0;
        StringBuffer result = new StringBuffer();
        result.append("{total:1,page:1,records:").append(size).append(",rows:[");
        if (size > 0) {
            for (TbDepartment dept : records) {
                result.append(this.asTreeString(dept, depth)).append(",");
            }
            result.delete(result.length() - 1, result.length());
        }
        return result.append("]}").toString();
    }
    
    private String asTreeString(TbDepartment dept, int depth) {
        StringBuffer result = new StringBuffer();
        result.append("{id:\"").append(dept.getDepartment_code()).append("\",cell:[");
        result.append("\"").append(dept.getDepartment_code()).append("\",");
        result.append("\"").append(dept.getDepartment_name()).append("\",");
        result.append("\"").append(dept.getParent_name() != null ? dept.getParent_name() : "").append("\",");
        result.append("\"").append(dept.getCreate_time() != null ? DateUtils.getTime(dept.getCreate_time()) : "")
                .append("\",");
        result.append("\"").append(dept.getModify_time() != null ? DateUtils.getTime(dept.getModify_time()) : "")
                .append("\",");
        result.append("\"").append(depth).append("\",");
        result.append("\"").append(dept.getParent_code() != null ? dept.getParent_code() : "").append("\",");
        result.append("\"false\",");
        result.append("\"false\"");
        result.append("]}");
        return result.toString();
    }
    
    public void setTbDepartmentDAO(TbDepartmentDAO tbDepartmentDAO) {
        this.tbDepartmentDAO = tbDepartmentDAO;
    }
}
